/**
 * API服务层 - 封装后端API调用
 * 提供规则模板、需求提交、AI对话等核心接口
 */
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log('API Response:', response.status, response.data)
    return response
  },
  (error) => {
    console.error('API Error Details:', {
      message: error.message,
      status: error.response?.status,
      data: error.response?.data,
      config: error.config,
      code: error.code
    })
    return Promise.reject(error)
  }
)

// 类型定义
export interface Template {
  id: string
  name: string
  content: string
  description?: string
  tags?: string[]
}

export interface RequirementData {
  template_id: string
  core_goal: string
  target_audience: string
  budget_per_person: string
  focus_point: string
  gift_preference?: string
  specific_product?: string
  customer_preference: string
  customer_pain_point: string
}

export interface RequirementResponse {
  success: boolean
  requirement_id: string
  prompt: string
}

export interface ChatRequest {
  requirement_id: string
  message?: string
  session_id: string
}

export interface ChatResponse {
  success: boolean
  content: string
  session_id: string
}

// API接口
export const templateApi = {
  // 获取规则模板列表
  getTemplates: async (): Promise<Template[]> => {
    const response = await api.get('/templates')
    // 后端返回的数据结构是 {data: {templates: [...]}}
    return response.data.data.templates || []
  }
}

export const requirementApi = {
  // 提交需求
  submit: async (data: RequirementData): Promise<RequirementResponse> => {
    const response = await api.post('/requirement/submit', data)
    return response.data
  },
  
  // 获取需求详情
  getById: async (requirementId: string) => {
    const response = await api.get(`/requirement/${requirementId}`)
    return response.data
  },
  
  // 获取需求列表
  getList: async () => {
    const response = await api.get('/requirements')
    return response.data
  }
}

export const chatApi = {
  // 生成AI内容
  generate: async (data: ChatRequest): Promise<ChatResponse> => {
    const response = await api.post('/chat/generate', data)
    return response.data
  },
  
  // 创建聊天会话
  createSession: async (requirementId: string) => {
    const response = await api.post('/chat/session', { requirement_id: requirementId })
    return response.data
  },
  
  // 获取会话历史
  getSessionHistory: async (sessionId: string) => {
    const response = await api.get(`/chat/session/${sessionId}`)
    return response.data
  },
  
  // 提交反馈
  submitFeedback: async (data: any) => {
    const response = await api.post('/chat/feedback', data)
    return response.data
  }
}

export default api